<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${pageTitle ?: '同步平台 - 编辑恢复任务'}">同步平台 - 编辑恢复任务</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar Navigation -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/}">
                                <i class="bi bi-house"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/dashboard}">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/server}">
                                <i class="bi bi-server"></i> 服务器管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/database}">
                                <i class="bi bi-database"></i> 数据库管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/database}">
                                <i class="bi bi-arrow-left-right"></i> 数据库同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/file}">
                                <i class="bi bi-files"></i> 文件同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" th:href="@{/restore}">
                                <i class="bi bi-arrow-counterclockwise"></i> 数据库恢复
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/task/log}">
                                <i class="bi bi-list-check"></i> 同步日志
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2" th:text="${task.id != null ? '编辑恢复任务' : '新建恢复任务'}">新建恢复任务</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a th:href="@{/restore}" class="btn btn-sm btn-outline-secondary">
                            <i class="bi bi-arrow-left"></i> 返回列表
                        </a>
                    </div>
                </div>
                
                <!-- Alert Messages -->
                <div class="alert alert-success alert-dismissible fade show" role="alert" id="successAlert" style="display: none;">
                    <span id="successMessage"></span>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                
                <div class="alert alert-danger alert-dismissible fade show" role="alert" id="errorAlert" style="display: none;">
                    <span id="errorMessage"></span>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                
                <!-- Edit Form -->
                <div class="card">
                    <div class="card-body">
                        <form id="taskForm" enctype="multipart/form-data">
                            <input type="hidden" id="taskId" name="id" th:value="${task.id}">
                            
                            <div class="mb-3">
                                <label for="name" class="form-label">任务名称</label>
                                <input type="text" class="form-control" id="name" name="name" 
                                       th:value="${task.name}" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="databaseId" class="form-label">目标数据库</label>
                                <select class="form-select" id="databaseId" name="databaseId" required>
                                    <option value="">选择目标数据库</option>
                                    <option th:each="db : ${databases}" 
                                            th:value="${db.id}" 
                                            th:text="${db.name}"
                                            th:selected="${task.databaseId == db.id}">
                                    </option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="description" class="form-label">任务描述</label>
                                <textarea class="form-control" id="description" name="description" 
                                          rows="3" th:text="${task.description}"></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="backupFile" class="form-label">备份文件</label>
                                <input type="file" class="form-control" id="backupFile" name="backupFile" 
                                       accept=".sql,.dump,.backup,.gz,.zip">
                                <div class="form-text">
                                    支持SQL文件、数据库备份文件等
                                    <span th:if="${task.originalFileName}" class="text-primary">
                                        当前文件: <span th:text="${task.originalFileName}"></span>
                                    </span>
                                </div>
                            </div>
                            
                            <div class="mb-3" th:if="${task.id != null}">
                                <label for="status" class="form-label">状态</label>
                                <select class="form-select" id="status" name="status">
                                    <option value="1" th:selected="${task.status == 1}">启用</option>
                                    <option value="0" th:selected="${task.status == 0}">禁用</option>
                                </select>
                            </div>
                            
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <a th:href="@{/restore}" class="btn btn-secondary me-md-2">取消</a>
                                <button type="button" id="saveButton" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                        
                        <div class="progress mt-3 d-none" id="uploadProgress">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
                
                <!-- Previous Backups Section (if editing) -->
                <div class="card mt-4" th:if="${task.id != null}">
                    <div class="card-header">
                        <h5 class="card-title mb-0">历史备份记录</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm table-hover" id="backupHistoryTable">
                                <thead>
                                    <tr>
                                        <th>备份文件</th>
                                        <th>创建时间</th>
                                        <th>上次执行</th>
                                        <th>结果</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="5" class="text-center">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.min.js"></script>
    <script th:src="@{/js/script.js}"></script>
    
    <script th:inline="javascript">
        $(document).ready(function() {
            const taskId = /*[[${task.id}]]*/ null;
            const databaseId = /*[[${task.databaseId}]]*/ null;
            
            // Save button click handler
            $('#saveButton').click(function() {
                // Validate form
                if (!$('#name').val() || !$('#databaseId').val()) {
                    $('#errorMessage').text('请填写所有必填字段');
                    $('#errorAlert').show();
                    return;
                }
                
                // Show progress bar if uploading file
                if ($('#backupFile').val()) {
                    $('#uploadProgress').removeClass('d-none');
                }
                
                // Get form data
                const formData = new FormData($('#taskForm')[0]);
                
                // Submit form
                $.ajax({
                    url: '/restore/save',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    xhr: function() {
                        const xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                const percent = Math.round((e.loaded / e.total) * 100);
                                $('#uploadProgress .progress-bar').css('width', percent + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#successMessage').text('保存成功');
                            $('#successAlert').show();
                            
                            // Redirect to list page after short delay
                            setTimeout(function() {
                                window.location.href = '/restore';
                            }, 1500);
                        } else {
                            $('#errorMessage').text('保存失败: ' + response.message);
                            $('#errorAlert').show();
                            $('#uploadProgress').addClass('d-none');
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#errorMessage').text('请求失败: ' + status + ' ' + error);
                        $('#errorAlert').show();
                        $('#uploadProgress').addClass('d-none');
                    }
                });
            });
            
            // Load backup history for editing page
            if (taskId && databaseId) {
                loadBackupHistory(databaseId);
            }
            
            function loadBackupHistory(dbId) {
                $.ajax({
                    url: '/restore/history/' + dbId,
                    type: 'GET',
                    success: function(response) {
                        if (response.success && response.data) {
                            updateBackupHistoryTable(response.data);
                        } else {
                            $('#backupHistoryTable tbody').html('<tr><td colspan="5" class="text-center">无历史备份记录</td></tr>');
                        }
                    },
                    error: function() {
                        $('#backupHistoryTable tbody').html('<tr><td colspan="5" class="text-center">加载历史记录失败</td></tr>');
                    }
                });
            }
            
            function updateBackupHistoryTable(historyData) {
                if (!historyData || historyData.length === 0) {
                    $('#backupHistoryTable tbody').html('<tr><td colspan="5" class="text-center">无历史备份记录</td></tr>');
                    return;
                }
                
                let tableHtml = '';
                
                historyData.forEach(function(item) {
                    const executionResult = item.lastExecutionResult === 1 ? 
                        '<span class="badge bg-success">成功</span>' : 
                        (item.lastExecutionResult === 0 ? '<span class="badge bg-danger">失败</span>' : '未执行');
                    
                    tableHtml += '<tr>';
                    tableHtml += '<td>' + (item.originalFileName || '未知文件') + '</td>';
                    tableHtml += '<td>' + formatDateTime(item.createTime) + '</td>';
                    tableHtml += '<td>' + (item.lastExecutionTime ? formatDateTime(item.lastExecutionTime) : '未执行') + '</td>';
                    tableHtml += '<td>' + executionResult + '</td>';
                    tableHtml += '<td>';
                    tableHtml += '<button class="btn btn-sm btn-outline-primary use-backup-btn" data-id="' + item.id + '">使用此备份</button>';
                    tableHtml += '</td>';
                    tableHtml += '</tr>';
                });
                
                $('#backupHistoryTable tbody').html(tableHtml);
                
                // Add event handlers for use backup buttons
                $('.use-backup-btn').click(function() {
                    const backupId = $(this).data('id');
                    $('#taskId').val(backupId);
                    $('#saveButton').click();
                });
            }
            
            function formatDateTime(dateTimeStr) {
                if (!dateTimeStr) return '';
                
                const date = new Date(dateTimeStr);
                
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }
        });
    </script>
</body>
</html> 